package com.example.whm;



import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.holoeverywhere.LayoutInflater;
import org.holoeverywhere.app.Activity;
import org.holoeverywhere.app.Application;
import org.holoeverywhere.app.Fragment;
import org.holoeverywhere.app.ProgressDialog;
import org.holoeverywhere.preference.SharedPreferences;
import org.holoeverywhere.widget.AdapterView;
import org.holoeverywhere.widget.ArrayAdapter;
import org.holoeverywhere.widget.CheckBox;
import org.holoeverywhere.widget.ListPopupWindow;
import org.holoeverywhere.widget.ListView;
import org.holoeverywhere.widget.Spinner;
import org.holoeverywhere.widget.TextView;
import org.holoeverywhere.widget.Toast;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.RadioGroup;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.example.whm.FourFragmentSubscribe.adapter2;
import com.example.whm.FourFragmentSubscribe.adapter3;
import com.example.whm.lib.box_Selection;
import com.example.whm.model.Address;
import com.example.whm.model.Box;
import com.example.whm.model.EntityBuy;
import com.example.whm.model.Item;
import com.example.whm.model.Order;
import com.example.whm.model.PreOrder;
import com.example.whm.model.SubscribeItem;
import com.example.whm.model.SubscribeRecord;


public class MySubscribeDetail extends Activity implements OnClickListener{

	private AQuery aq; 
	private AQuery aq2;
	
	private String topic;
	Address add;
	Map<String, String> map;
	List<Order> boxs;
	int num=0;
	int price=0;
	int tag;
	box_Selection mCallback;
	Spinner sp;
	ListPopupWindow popup;
	
	RadioGroup radioButtonGroup;
	ProgressDialog dialog;
	adapter adap;
	adapter2 adap2;
	TextView num_t;
	TextView price_t;
	List<CheckBox> check_list=new ArrayList<CheckBox>();
	SubscribeRecord sub;
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//setTheme(R.style.Holo_Theme_Light); 
		
		//setTheme(R.style.StyledIndicators); 
		//getSupportActionBar().hide();
		
		//requestWindowFeature(Window.FEATURE_NO_TITLE);
		// setSupportProgressBarVisibility(false);
		setContentView(R.layout.myorder_detail);
		aq = new AQuery(this);		
		 Bundle b= getIntent().getExtras();
		 if (b!=null) {
			 Log.i("EntityDetail", "getIntent().getExtras()  id="+b.getString("sub"));
			 sub=JSONObject.parseObject(b.getString("sub"), SubscribeRecord.class);
			 ui();
		}
		
		
	}








	ListView list;
public void init(){
	
	  String url="http://"+Whm_app.api_url+":9000/api/user_order";
	  AjaxCallback<String> cb = new AjaxCallback<String>();        
	  cb.url(url).type(String.class).weakHandler(this, "ui");
	  SharedPreferences sp=((Application)getApplication()).getSharedPreferences("whm",Context.MODE_PRIVATE);
  	String cookiename=sp.getString("cookie_name",null);
  	String cookievalue=sp.getString("cookie_value",null);
  	if (cookiename!=null&&cookievalue!=null) {
  		cb.cookie(cookiename,cookievalue);               
	}
	  aq.ajax(cb);
  }

  public void ui(){
	
		  new Thread( new Runnable() {
			  @Override
			public void run() {
				  // String s1= JSON.parseObject(s).getString("users");
			
				  
				 runOnUiThread(new Runnable() {
					  
					  @Override
					  public void run() {
						
						  aq.id(R.id.progress).gone();
						//  aq2.id(R.id.four_layout_line).visible();
						  
						//   list=(ListView) aq2.id(R.id.myorder_fragment_listview).getListView();
						/*  View v=MySubscribeDetail.this.getLayoutInflater().inflate(R.layout.mypreorder_detail_footview, null);
						  AQuery a=new AQuery(v);
						 
						  a.id(R.id.myorder_detail_foot_area).text(order.getCity_area());
						  a.id(R.id.myorder_detail_foot_address).text(order.getAddress());
						  a.id(R.id.myorder_detail_foot_contactname).text(order.getContactname());
						  a.id(R.id.myorder_detail_foot_phone).text(order.getPhone());
						  aq.id(R.id.myorder_detail_listview).getListView().addFooterView(v);*/
						  /*  View v2=MySubscribeDetail.this.getLayoutInflater().inflate(R.layout.four_layout_footer, null);
						   AQuery a=new AQuery(v);
						  AQuery a2=new AQuery(v2);
						  a.id(R.id.four_layout_contact_name).text(add.getContact_name());
						  a.id(R.id.four_layout_contact_phone).text(add.getPhone());
						  a.id(R.id.four_layout_contact_addr).text(add.getDetail_address());
						  a2.find(R.id.four_layout_btn_sure).clicked(MyOrderFragment.this); 
						   radioButtonGroup=(RadioGroup) a.find(R.id.four_layout_pay).getView();
						  list.addHeaderView(v);
						  list.addFooterView(v2);*/
						 
						  adap=new adapter(sub.getSub_items());
						  aq.id(R.id.myorder_detail_listview).adapter(adap);						 
						  //Utility.setListViewHeightBasedOnChildren(list);
					  }
				  });
			  }
		  }).start();
			
		  
	
	  
  }

  
  class adapter extends BaseAdapter{

		
	  
		List<SubscribeItem> list;
		public adapter() {
			super();
			// TODO Auto-generated constructor stub
		}
	   
		
		public adapter(List<SubscribeItem> list) {
			super();
			this.list = list;
		}

		
		

		public List<SubscribeItem> getList() {
			return list;
		}


		public void setList(List<SubscribeItem> list) {
			this.list = list;
		}


		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return list.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			// TODO Auto-generated method stub
		
			//System.out.println("adapter arg0---------------"+arg0);
			if(arg1 == null){
				arg1 = aq.inflate(arg1, R.layout.mysubscribe_detail_fragment_list_item_sub, arg2);
			}
			
	
			SubscribeItem i = (SubscribeItem) getItem(arg0);
		    
			AQuery aq2 = aq.recycle(arg1);
			aq2.id(R.id.four_layout_item_sub).text(i.getDetail_date());
			aq2.id(R.id.four_layout_item_sub_price).text(String.valueOf(i.getPrice()));
			aq2.id(R.id.four_layout_item_sub_grid).adapter(new adapter3(i.getList()));
		
			return arg1;		 
		}
		
		
	}

  
 
  class adapter3 extends BaseAdapter{

		
		List<EntityBuy> list;
		public adapter3() {
			super();
			// TODO Auto-generated constructor stub
		}
	   
		
		public adapter3(List<EntityBuy> list) {
			super();
			this.list = list;
		}


		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return list.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			// TODO Auto-generated method stub
		
			//System.out.println("adapter3 arg0---------------"+arg0);
			if(arg1 == null){
				arg1 = aq.inflate(arg1, R.layout.three_layout_grid_item, arg2);
			}
			
			
			EntityBuy i = (EntityBuy) getItem(arg0);

			AQuery aq2 = aq.recycle(arg1);
		    aq2.id(R.id.three_layout_grid_item_text).text(i.getEntity().getName());
			String tbUrl = i.getEntity().getPre_pic().replace("localhost", Whm_app.api_url);
		
			if(aq2.shouldDelay(arg0, arg1, arg2, tbUrl)){
				aq2.id(R.id.three_layout_grid_item_imagevie).clear();
			}else{
				aq2.id(R.id.three_layout_grid_item_imagevie).image(tbUrl, true, true, 200, R.drawable.ic_launcher, null,0, 0);
			}
			
			
			return arg1;
		}
		
		
	}
  
  
  
  
  
  
  
  
  
  
 
  public void showListPopup(View anchor) {
      popup = new ListPopupWindow(MySubscribeDetail.this);
      popup.setAnchorView(anchor);
      ArrayAdapter<String> adapter = new ArrayAdapter<String>(MySubscribeDetail.this,android.R.layout.simple_list_item_2);  
      adapter.add("order");  
      adapter.add("preorder");  
      adapter.add("subscribe");    
      popup.setAdapter(adapter);
      ListView list=popup.getListView();
      
  //    popup.setWidth(300);
   //   popup.setHeight(400);
    // list.setOnItemSelectedListener();
      //list.setOnItemClickListener(FourFragmentOrder.this);
      //.setOnItemClickListener(FourFragmentOrder.this);
      
  }
  
  
  public void makeMenu(Menu menu, MenuInflater inflater) {
      if (menu instanceof ContextMenu) {
          ((ContextMenu) menu).setHeaderTitle("Context menu title");
      }
      menu.clear();
      inflater.inflate(R.menu.menu, menu);
      for (int i = 0; i < menu.size(); i++) {
          menu.getItem(i).setOnMenuItemClickListener(mOnMenuItemClickListener);
      }
     
  }
  
  private final OnMenuItemClickListener mOnMenuItemClickListener = new OnMenuItemClickListener() {
      @Override
      public boolean onMenuItemClick(MenuItem menuItem) {
          boolean result = false;
          final int id = menuItem.getItemId();
          if (menuItem.getTitle().equals("order")) {
        	  mCallback.show_boxf(0);
		  }
          if (menuItem.getTitle().equals("preorder")) {       
        	  mCallback.show_boxf(1);
          }
          if (menuItem.getTitle().equals("subscribe")) {        	  
        	  mCallback.show_boxf(2);
          }
          //  System.out.println("onMenuItemClick id========="+id);
          return true;
      }
  };
  
  




public void show_dialog(boolean b){
	
	if (dialog==null) {
		dialog = new ProgressDialog(MySubscribeDetail.this);
	    dialog.setIndeterminate(true);
	    dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	    dialog.setMessage("post");
	}
	if (b) {
		dialog.show();
	}else{
		dialog.dismiss();
	} 
    
}


boolean is_check=true;
List<String> ids=new ArrayList<String>();
List<Box> ids_box=new ArrayList<Box>();


@Override
public void onClick(View v) {
	// TODO Auto-generated method stub
	switch (v.getId()) {  
  
    
    	
    default:  
        break;  
    }  
}




public void buy_sure(){
 
			// TODO Auto-generated method stub
			 show_dialog(true);
			int radioButtonID = radioButtonGroup.getCheckedRadioButtonId();
			View radioButton = radioButtonGroup.findViewById(radioButtonID);
			int idx = radioButtonGroup.indexOfChild(radioButton);
			
			  Map<String, Object> params = new HashMap<String, Object>();
			    params.put("type", idx+1);
			    params.put("tag", 1);
			    params.put("address_id", add.getId());
			  System.out.println("buy_sure===="+JSON.toJSONString(params));
			    
			String url="http://"+Whm_app.api_url+":9000/api/buy_sure_func";
			  AjaxCallback<String> cb = new AjaxCallback<String>();        
			  cb.url(url).type(String.class).weakHandler(this, "sure_func_result");
			  cb.params(params);
			  SharedPreferences sp=((Application)MySubscribeDetail.this.getApplication()).getSharedPreferences("whm",Context.MODE_PRIVATE);
			String cookiename=sp.getString("cookie_name",null);
			String cookievalue=sp.getString("cookie_value",null);
			if (cookiename!=null&&cookievalue!=null) {
				cb.cookie(cookiename,cookievalue);               
			}
		    aq.ajax(cb);
		
	
	
}

public void sure_func_result(String url, String r, AjaxStatus status){
	  show_dialog(false);
	  //System.out.println("sure_func_result========="+r);
	//  System.out.println("sure_func_result status.getCode()========="+status.getCode());
	//  System.out.println("sure_func_result url========="+url);
	  if (status.getCode()==200) {
		
		 String re=JSON.parseObject(r).getString("result");
		 if (re.equals("ok")) {
		     refresh_list();
		}else if(re.equals("login_error")){
			
			Toast.makeText(MySubscribeDetail.this, String.valueOf("login error,please again"), 1000).show();
		}
		 
	 }else{		 
		 Toast.makeText(MySubscribeDetail.this, String.valueOf("post error,please again"), 1000).show();
	 }
}

public void refresh_list(){
	  MySubscribeDetail.this.runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				 
				 num=0;
					price=0;
					 num_t.setText(String.valueOf(num));
					 price_t.setText(String.valueOf(price));
				 adap2.getList().clear();
				 adap2.notifyDataSetChanged();
				 adap.notifyDataSetChanged();
			
			}
		});
	
}

public void refresh(){
	show_dialog(true);
	init();
	
}




    
 
}
